package site.haoyin.bluetoothdemo.activity;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import site.haoyin.bluetoothdemo.R;
import site.haoyin.bluetoothdemo.bean.DeviceScanBean;
import site.haoyin.bluetoothdemo.config.Constants;
import site.haoyin.bluetoothdemo.utils.SharePreferecnceUtils;
import site.haoyin.bluetoothdemo.utils.ToastUtil;

import com.google.gson.Gson;

import site.haoyin.lib.CXComm;
import site.haoyin.lib.bluetooth.CXBlueTooth;
import site.haoyin.lib.bluetooth.listener.IBlueToothListener;
import site.haoyin.lib.bluetooth.listener.IReceiveDataListener;
import site.haoyin.lib.cpcl.CXCpcl;
import site.haoyin.lib.escpos.CXEscpos;
import site.haoyin.lib.tspl.CXTspl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import site.haoyin.lib.utils.ByteUtil;


public class MainActivity extends AppCompatActivity {
    @BindView(R.id.title_bar)
    RelativeLayout mTitle_bar;
    @BindView(R.id.iv_left)
    ImageView mImg_left;
    @BindView(R.id.iv_right)
    ImageView mImg_right;
    @BindView(R.id.tv_title)
    TextView mTv_title;
    @BindView(R.id.recyclerview)
    RecyclerView mRecycleView;
    @BindView(R.id.btn_disconnet)
    Button mBtn_disconnet;
    @BindView(R.id.btn_senddata)
    Button mBtn_senddata;
    @BindView(R.id.tv_none)
    TextView mTv_none;
    @BindView(R.id.tv_content)
    TextView mTv_content;
    @BindView(R.id.rl_connectdevicename)
    RelativeLayout mRl_connectdevicename;
    private static String TAG = MainActivity.class.getSimpleName();
    private static final int MSG_START_SCAN = 1001;
    private static final int MSG_STOP_SCAN = 1002;
    private static final int MSG_START_ACTIVITY = 1004;
    private static final int MSG_CONNECT_FAIL = 1005;
    private static final int MSG_CONNECTED = 1006;
    private static final int MSG_DISCONNECTED = 1007;
    private ProgressDialog mProgressDialog;
    private ConnectDeviceRecyleViewAdapter mAdapter;
    private boolean isConnecting = false;
    private boolean isConnect = false;
    private DeviceScanBean clickDeviceScanBean;
    private ArrayList<DeviceScanBean> lists = new ArrayList<DeviceScanBean>();
    private List<String> deniedPermissions = new ArrayList<>();
    private PRINTERLANGUAGE printerlanguage = PRINTERLANGUAGE.CPCL;
    private CXTspl cxTspl;

    private enum PRINTERLANGUAGE {
        CPCL,
        TSPL,
        ESCPOS;
    }

    //新建BroadcastReceiver
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
//            Log.e(TAG, "onReceive: " + action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//                Log.e(TAG, "onReceive: " + "ACTION_FOUND");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getName() != null) {

                }
                for (DeviceScanBean list : lists) {
                    if (list.getBluetoothDevice().getAddress().equals(device.getAddress())) {
                        return;
                    }
                }
                if (isConnect) {
                    if ((device.getType() == BluetoothDevice.DEVICE_TYPE_CLASSIC || device.getType() == BluetoothDevice.DEVICE_TYPE_DUAL)
                            && !((device.getBluetoothClass().getDeviceClass()) == BluetoothClass.Device.PHONE_SMART)) {
                        lists.add(new DeviceScanBean(device, 0, new byte[0]));
                        mAdapter.setData(lists);
                        if (lists.size() != 0) {
                            mTv_none.setVisibility(View.GONE);
                        }
                        mAdapter.setConnectList(deviceScanBeanSharePre);
                    }
                } else {
                    if ((device.getType() == BluetoothDevice.DEVICE_TYPE_CLASSIC || device.getType() == BluetoothDevice.DEVICE_TYPE_DUAL)
                            && !((device.getBluetoothClass().getDeviceClass()) == BluetoothClass.Device.PHONE_SMART)) {
                        lists.add(new DeviceScanBean(device, 0, new byte[0]));
                        mAdapter.setData(lists);
                        if (lists.size() != 0) {
                            mTv_none.setVisibility(View.GONE);
                        }
                    }
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (mImg_right != null) {
                    mImg_right.clearAnimation();
                }
            }
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_START_SCAN:
                    startScan();
                    break;
                case MSG_CONNECTED:
                    setConnected();
                    break;
                case MSG_DISCONNECTED:
                    setDisConected();
                    break;
                case MSG_STOP_SCAN:
                    dismissDialog();
                case MSG_START_ACTIVITY:
                    break;
                case MSG_CONNECT_FAIL:
                    break;
                default:
                    break;
            }
        }

    };

    private DeviceScanBean deviceScanBean;
    private Context mContext;
    private DeviceScanBean deviceScanBeanSharePre;
    private Unbinder bind;
    private ArrayList<byte[]> mQueue;
    private CXBlueTooth BT;
    private CXComm cxcomm;
    private CXCpcl cxCpcl;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bind = ButterKnife.bind(this);
        requestPermissions();
        initUI();
        initRecyleView();
        BT = CXBlueTooth.getInstance();
        cxcomm = BT;
        cxcomm.recv(new IReceiveDataListener() {
            @Override
            public void onReceiveData(byte[] data) {
                //接收蓝牙发送的消息
                try {
                    int len = ByteUtil.returnActualLength(data);
                    byte[] actualData = new byte[len];
                    System.arraycopy(data, 0, actualData, 0, len);
                    String content = new String(actualData, "utf-8");
                    Log.e(TAG, "actualDataLen:" + actualData.length + "content==" + content);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });

        BT.setBlueToothListener(new IBlueToothListener() {
            @Override
            public void onConnected() {
                mHandler.sendEmptyMessageDelayed(MSG_CONNECTED, 1000);
            }

            @Override
            public void onDisConnected() {
                mHandler.sendEmptyMessageDelayed(MSG_DISCONNECTED, 1000);
            }

            @Override
            public void onError() {
                mHandler.sendEmptyMessageDelayed(MSG_DISCONNECTED, 1000);
            }
        });

        registerReceiver(receiver, getIntentFilter());
        String source = SharePreferecnceUtils.getConectDevice();
        if (!TextUtils.isEmpty(source)) {
            boolean connected = BT.isConnected();
            if (connected) {
                mRl_connectdevicename.setVisibility(View.VISIBLE);
                mBtn_disconnet.setBackground(ContextCompat.getDrawable(this, R.drawable.bg_setting_check));
                mBtn_senddata.setBackground(ContextCompat.getDrawable(this, R.drawable.bg_setting_check));
                isConnect = true;
                try {
                    deviceScanBeanSharePre = new Gson().fromJson(source, DeviceScanBean.class);
                    mTv_content.setText(deviceScanBeanSharePre.getDeviceName() + "\r\n" + deviceScanBeanSharePre.getMacAddress());
                } catch (Exception e) {


                }
            } else {
                mRl_connectdevicename.setVisibility(View.GONE);
                mBtn_disconnet.setBackground(ContextCompat.getDrawable(this, R.drawable.bg_setting_normal));
                mBtn_senddata.setBackground(ContextCompat.getDrawable(this, R.drawable.bg_setting_normal));
            }
        }
        openBle();
    }

    private void setConnected() {
        isConnecting = false;
        isConnect = true;
        clickDeviceScanBean = null;
        if (deviceScanBean != null) {
            if (!TextUtils.isEmpty(deviceScanBean.getDeviceName()) && !TextUtils.isEmpty(deviceScanBean.getMacAddress()))
                mTv_content.setText(deviceScanBean.getDeviceName() + "\r\n" + deviceScanBean.getMacAddress());
            mRl_connectdevicename.setVisibility(View.VISIBLE);
            Log.e(TAG, "data==" + new Gson().toJson(deviceScanBean));
            SharePreferecnceUtils.setConnectDevicee(new Gson().toJson(deviceScanBean));
        }
        if (mContext != null) {
            mBtn_disconnet.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_setting_check));
            mBtn_senddata.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_setting_check));
//                    mAdapter.notifyDataSetChanged();
            if (deviceScanBean != null) {
                mAdapter.setConnectList(deviceScanBean);
            }
        }
        CXBlueTooth.getInstance().setConnected(true);
    }

    private void setDisConected() {
        isConnecting = false;
        isConnect = false;
        mAdapter.notifyDataSetChanged();
        CXBlueTooth.getInstance().setConnected(false);
    }

    private void requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            deniedPermissions.clear();
            List<String> permissions = findDeniedPermissions(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), 101);
            }
            int hasFineLocationPermission = this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
            if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED) {
            }
        } else {

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 101) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    deniedPermissions.add(permissions[i]);
                } else {
                    if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    }
                }
            }
            String msg = null;
            for (String str : deniedPermissions) {
                if (str.equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    if (TextUtils.isEmpty(msg)) {
                        msg = getString(R.string.permissions_read);
                    } else {
                        msg = msg + "," + getString(R.string.permissions_read);
                    }
                } else if (str.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    if (TextUtils.isEmpty(msg)) {
                        msg = getString(R.string.permissions_write);
                    } else {
                        msg = msg + "," + getString(R.string.permissions_write);
                    }
                } else if (str.equals(Manifest.permission.ACCESS_COARSE_LOCATION) || str.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    if (TextUtils.isEmpty(msg)) {
                        msg = getString(R.string.permissions_gps);
                    } else {
                        if (!msg.contains(getString(R.string.permissions_gps))) {
                            msg = msg + "," + getString(R.string.permissions_gps);
                        }
                    }
                }
            }
            if (!TextUtils.isEmpty(msg)) {
                Toast.makeText(MainActivity.this, msg + getString(R.string.permissions_setting), Toast.LENGTH_LONG).show();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public List<String> findDeniedPermissions(String... permission) {
        List<String> denyPermissions = new ArrayList<>();
        for (String value : permission) {
            if (checkSelfPermission(value) != PackageManager.PERMISSION_GRANTED) {
                denyPermissions.add(value);
            }
        }
        return denyPermissions;
    }


    private void openBle() {
        if (CXBlueTooth.getInstance().isBlueToothOpen()) {
            startScan();
        } else {
            Log.e("openBle", "false");
            startActivityForResult((new Intent(this, OpenBleActivity.class)),
                    Constants.REQUESTCODE_OPEN_BLE);
        }
    }

    private void initRecyleView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setLayoutManager(layoutManager);
        mAdapter = new ConnectDeviceRecyleViewAdapter(this);
        mRecycleView.setAdapter(mAdapter);
    }

    private void initUI() {
        mContext = this;
        mImg_right.setImageResource(R.mipmap.ic_refresh);
        mImg_right.setVisibility(View.VISIBLE);
        mTv_title.setText(R.string.connectdevice_title);
    }

    public void dismissDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    //新建一个IntentFilter
    private IntentFilter getIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        return intentFilter;
    }

    @OnClick({R.id.lay_left, R.id.lay_right, R.id.btn_disconnet, R.id.btn_senddata, R.id.tvPrint1, R.id.tvPrint2, R.id.tvPrint3})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_left:
                finish();
                break;
            case R.id.lay_right:
                startScan();
                break;
            case R.id.btn_disconnet:
                if (isConnect) {
                    mBtn_disconnet.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_setting_normal));
                    mBtn_senddata.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_setting_normal));
                    isConnect = false;
                    isConnecting = false;
                    clickDeviceScanBean = null;
                    CXBlueTooth.getInstance().disconnect();
                    mRl_connectdevicename.setVisibility(View.GONE);
                    mAdapter.setData(lists);
                    mAdapter.notifyDataSetChanged();
                    SharePreferecnceUtils.setConnectDevicee("");
//                    sendBroadcast(new Intent(Constants.ACTION_SPPDISCONNECT));
                }
                break;
            case R.id.btn_senddata:
                if (printerlanguage == PRINTERLANGUAGE.TSPL) {
                    sendTsplDataLabelBig();
                } else if (printerlanguage == PRINTERLANGUAGE.CPCL) {
                    sendCpclData();
                } else if (printerlanguage == PRINTERLANGUAGE.ESCPOS) {
                    sendEscposData();
                }
                break;
            case R.id.tvPrint1:
                sendTsplData();
                break;
            case R.id.tvPrint2:
                sendTsplDataEd();
                break;
            case R.id.tvPrint3:
                sendTsplDataLabel();
                break;
                // 测试支付
            case R.id.tvPrint4:

                break;
        }
    }


    private void sendEscposData() {
        CXEscpos cxEscpos = CXEscpos.getInstance(cxcomm, 0);
        /*初始化打印机*/
        cxEscpos.InitializePrinter();
        /*走纸开关*/
        cxEscpos.PrintAndFeedLines((byte) 3);
        /* 设置打印居中 */
        cxEscpos.SelectJustification(CXEscpos.JUSTIFICATION.CENTER);
        /* 设置为倍高倍宽 */
        cxEscpos.SelectPrintModes(CXEscpos.FONT.FONTA, CXEscpos.ENABLE.OFF, CXEscpos.ENABLE.ON, CXEscpos.ENABLE.ON, CXEscpos.ENABLE.OFF);
        /* 打印文字 */
        cxEscpos.Text("Sample\n");
        /* 打印并换行*/
        cxEscpos.PrintAndLineFeed();
        /* 打印文字 */
        /* 取消倍高倍宽 */
        cxEscpos.SelectPrintModes(CXEscpos.FONT.FONTA, CXEscpos.ENABLE.OFF, CXEscpos.ENABLE.OFF, CXEscpos.ENABLE.OFF, CXEscpos.ENABLE.OFF);
        /* 设置打印左对齐 */
        cxEscpos.SelectJustification(CXEscpos.JUSTIFICATION.LEFT);
        /* 打印文字 */
        cxEscpos.Text("Print text\n");
        /* 打印文字 */
        cxEscpos.Text("Welcome to use CX printer!\n");
        /* 打印繁体中文 需要打印机支持繁体字库 */
        String message = "宸芯票据打印机\n";
        cxEscpos.Text(message);
        cxEscpos.PrintAndLineFeed();

        /* 绝对位置  */
        cxEscpos.Text("智能");
        cxEscpos.SetHorAndVerMotionUnits((byte) 7, (byte) 0);
        cxEscpos.SetAbsolutePrintPosition((short) 6);
        cxEscpos.Text("网络");
        cxEscpos.SetAbsolutePrintPosition((short) 10);
        cxEscpos.Text("设备");
        cxEscpos.PrintAndLineFeed();

        /* 打印图片 */
        /* 打印文字 */
        cxEscpos.Text("Print bitmap!\n");
        Bitmap b = BitmapFactory.decodeResource(getResources(),
                R.drawable.cxprinter);
        /* 打印图片 */
        cxEscpos.Bitmap(100, 100, 200, 250, b, CXEscpos.BITMAP_MODE.MODE0.getValue());

        /* 打印一维条码 */
        /* 打印文字 */
        cxEscpos.Text("Print code128\n");
        cxEscpos.addSelectPrintingPositionForHRICharacters(CXEscpos.HRI_POSITION.BELOW);
        /*
         * 设置条码可识别字符位置在条码下方
         * 设置条码高度为60点
         */
        cxEscpos.addSetBarcodeHeight((byte) 60);
        /* 设置条码单元宽度为1 */
        cxEscpos.addSetBarcodeWidth((byte) 1);
        /* 打印Code128码 */
        cxEscpos.addCODE128(cxEscpos.genCodeB("CXPrinter"));
        cxEscpos.PrintAndLineFeed();

        /*
         * QRCode命令打印 此命令只在支持QRCode命令打印的机型才能使用。 在不支持二维码指令打印的机型上，则需要发送二维条码图片
         */
        /* 打印文字 */
        cxEscpos.Text("Print QRcode\n");
        /* 设置纠错等级 */
        cxEscpos.addSelectErrorCorrectionLevelForQRCode((byte) 0x31);
        /* 设置qrcode模块大小 */
        cxEscpos.addSelectSizeOfModuleForQRCode((byte) 3);
        /* 设置qrcode内容 */
        cxEscpos.addStoreQRCodeData("www.baidu.com");
        cxEscpos.addPrintQRCode(); /* 打印QRCode */
        cxEscpos.PrintAndLineFeed();

        cxEscpos.Line(0, 88, 576, 88, 1);
        cxEscpos.Line(0, 216, 576, 216, 1);
        cxEscpos.Line(0, 296, 576, 296, 1);
        cxEscpos.Line(0, 440, 528, 440, 1);
        cxEscpos.Line(0, 568, 528, 568, 1);
        cxEscpos.Line(0, 664, 528, 664, 1);
        cxEscpos.Line(528, 296, 528, 664, 1);
        cxEscpos.Line(48, 296, 48, 568, 1);
        /* 设置打印左对齐 */
        cxEscpos.SelectJustification(CXEscpos.JUSTIFICATION.CENTER);
        /* 打印文字 */
        cxEscpos.Text("Completed!\r\n");
        cxEscpos.PrintAndFeedLines((byte) 8);
    }

    @OnClick({R.id.radio_cpcl, R.id.radio_tspl, R.id.radio_escpos})
    public void onRadioButtonClick(RadioButton radioButton) {
        switch (radioButton.getId()) {
            case R.id.radio_cpcl:
                printerlanguage = PRINTERLANGUAGE.CPCL;
                break;
            case R.id.radio_tspl:
                printerlanguage = PRINTERLANGUAGE.TSPL;
                break;
            case R.id.radio_escpos:
                printerlanguage = PRINTERLANGUAGE.ESCPOS;
                break;
        }
    }

    private void sendTsplDataLabelBig() {
        cxTspl = CXTspl.getInstance(cxcomm, 0);
        cxTspl.PrintAreaSize(0, 200, 200, 75 * 8, 50 * 8, 1);
        /* 清除打印缓冲区 */
        cxTspl.Cls();
        /* 绘制直线 */
        cxTspl.Line(0, 0, 600, 2);
        cxTspl.Line(0, 12, 600, 2);
        /* 绘制简体中文，以英寸为单位39约为1cm，字体以点为单位24大约3mm*/
        cxTspl.Text(248, 50, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "旋转0度\n");

        /* 绘制简体中文，以英寸为单位39约为1cm，字体以点为单位24大约3mm*/
        cxTspl.Text(176, 90, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_90, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "旋转90度\n");

        /* 绘制简体中文，以英寸为单位39约为1cm，字体以点为单位24大约3mm*/
        cxTspl.Text(341, 350, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_180, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "旋转180度\n");
        /* 绘制简体中文，以英寸为单位39约为1cm，字体以点为单位24大约3mm*/
        cxTspl.Text(401, 215, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_270, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "旋转270度\n");
        /* 绘制二维码 */
        /* 绘制二维码 */
        cxTspl.QRCode(236, 100, CXTspl.EEC.LEVEL_L, 5, CXTspl.ROTATION.ROTATION_0, "202019865425613");

        /* 绘制一维条码 */
        cxTspl.Barcode(156, 230, CXTspl.BARCODETYPE.CODE128, 60, CXTspl.READABEL.EANBEL, CXTspl.ROTATION.ROTATION_0, "202019865425613");

        /* 打印标签 */
        cxTspl.Print(1, 1);
    }

    private void sendTsplDataLabel() {
        cxTspl = CXTspl.getInstance(cxcomm, 0);
        cxTspl.PrintAreaSize(0, 200, 200, 50 * 8, 40 * 8, 1);
        /* 清除打印缓冲区 */
        cxTspl.Cls();
        /* 绘制直线 */
        cxTspl.Line(0, 0, 400, 2);
        cxTspl.Line(0, 12, 400, 2);
        /* 绘制简体中文，以英寸为单位39约为1cm，字体以点为单位24大约3mm*/
        cxTspl.Text(152, 30, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "旋转0度\n");

        /* 绘制简体中文，以英寸为单位39约为1cm，字体以点为单位24大约3mm*/
        cxTspl.Text(80, 60, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_90, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "旋转90度\n");

        /* 绘制简体中文，以英寸为单位39约为1cm，字体以点为单位24大约3mm*/
        cxTspl.Text(245, 310, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_180, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "旋转180度\n");
        /* 绘制简体中文，以英寸为单位39约为1cm，字体以点为单位24大约3mm*/
        cxTspl.Text(305, 175, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_270, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "旋转270度\n");
        /* 绘制二维码 */
        cxTspl.QRCode(140, 60, CXTspl.EEC.LEVEL_L, 5, CXTspl.ROTATION.ROTATION_0, "202019865425613");

        /* 绘制一维条码 */
        cxTspl.Barcode(60, 190, CXTspl.BARCODETYPE.CODE128, 60, CXTspl.READABEL.EANBEL, CXTspl.ROTATION.ROTATION_0, "202019865425613");

//        cxTspl.Line(0, 319, 400, 1);

        /* 打印标签 */
        cxTspl.Print(1, 1);
    }


    private void sendTsplDataEd() {
        cxTspl = CXTspl.getInstance(cxcomm, 0);
        cxTspl.PrintAreaSize(0, 200, 200, 72, 120, 1);
        /* 清除打印缓冲区 */
        cxTspl.Cls();
        /* 绘制简体中文，以英寸为单位39约为1cm，字体以点为单位24大约3mm*/
        cxTspl.Text(500, 0, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "标 准\n");
        cxTspl.Text(500, 25, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "快 递\n");
        cxTspl.Text(0, 50, CXTspl.FONTTYPE.FONT_1, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "2020-12-17  12:23:51 第1/1\n");
        cxTspl.Box(0, 65, 576, 880, 1);
        /* 绘制一维条码 */
        cxTspl.Barcode(160, 80, CXTspl.BARCODETYPE.CODE128, 100, CXTspl.READABEL.EANBEL, CXTspl.ROTATION.ROTATION_0, "202019865425613");
        /* 绘制直线 */
        cxTspl.Line(0, 225, 576, 1);

        cxTspl.Text(20, 240, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_2, CXTspl.FONTMUL.MUL_2,
                "01 02 03(测试打印)\n");
        /* 绘制直线 */
        cxTspl.Line(0, 290, 576, 1);

        cxTspl.Text(10, 300, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "集 浙江杭州南星桥公司\n");
        /* 绘制直线 */
        cxTspl.Line(0, 340, 440, 1);

        cxTspl.Text(10, 350, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "收 火先生 138000001111\n");

        cxTspl.Text(10, 390, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "浙江省杭州市西湖区文三路伟星大厦9D\n");
        /* 绘制直线 */
        cxTspl.Line(0, 540, 576, 1);

        cxTspl.Text(10, 550, CXTspl.FONTTYPE.FONT_1, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "寄 冯先生 188888888888 上海市黄浦区南京西路281号人民公园6栋308室\n");
        /* 绘制直线 */
        cxTspl.Line(440, 440, 136, 1);
        /* 绘制直线 */
        cxTspl.Line(0, 590, 576, 1);
        /* 绘制直线 */
        cxTspl.Line(440, 290, 1, 300);

        /* 绘制直线 */
        cxTspl.Line(160, 590, 1, 130);
        /* 绘制二维码 */
        cxTspl.QRCode(20, 600, CXTspl.EEC.LEVEL_L, 5, CXTspl.ROTATION.ROTATION_0, "202019865425613");

        /* 绘制一维条码 */
        cxTspl.Barcode(240, 600, CXTspl.BARCODETYPE.CODE128, 80, CXTspl.READABEL.EANBEL, CXTspl.ROTATION.ROTATION_0, "202019865425613");

        /* 绘制直线 */
        cxTspl.Line(0, 720, 576, 1);
        cxTspl.Text(10, 730, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "一件衣服(测试打印)\n");
        cxTspl.Text(10, 730, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "一件衣服(测试打印)\n");
        cxTspl.Text(460, 820, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "品类:服饰\n");
        cxTspl.Text(500, 850, CXTspl.FONTTYPE.FONT_2, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "已验视\n");
        /* 打印标签 */
        cxTspl.Print(1, 1);
    }

    private void sendTsplData() {
        cxTspl = CXTspl.getInstance(cxcomm, 0);
        cxTspl.getDeviceInfo();
        cxTspl.setSelf();
        /* 设置标签尺寸，按照实际尺寸设置，以mm为单位 */
        cxTspl.PrintAreaSize(0, 0, 0, 72 * 8, 200, 1);
//            /* 设置标签间隙，按照实际尺寸设置，如果为无间隙纸则设置为0，以mm为单位 */
//            cxTspl.Gap( 20 );
        /* 换页所需的黑线的高度 */
//            cxTspl.Bline( 80, 100);
        /* 设置浓度 */
        cxTspl.Density(CXTspl.DENSITY.DNESITY15.getValue());
        /* 设置打印速度 */
        cxTspl.Speed(CXTspl.SPEED.SPEED1DIV5);
        /* 设置打印方向 */
        cxTspl.Direction(CXTspl.DIRECTION.FORWARD, CXTspl.MIRROR.NORMAL);
        /* 设置原点坐标 */
        cxTspl.Reference(0, 0);
        /* 清除打印缓冲区 */
        cxTspl.Cls();
        /* 绘制简体中文，以英寸为单位39约为1cm，字体以点为单位24大约3mm*/
        cxTspl.Text(0, 40, CXTspl.FONTTYPE.FONT_0, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "金黄蕉(福门).老挝.箱装");
        cxTspl.Text(0, 40 + 24 + 6, CXTspl.FONTTYPE.FONT_1, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1,
                "果速送2019-04-24 09:39:40");
        cxTspl.Text(0, 0, CXTspl.FONTTYPE.FONT_ROMANTTF, CXTspl.ROTATION.ROTATION_0, CXTspl.FONTMUL.MUL_1, CXTspl.FONTMUL.MUL_1, CXTspl.ALIGNMENT.ALIGNRIGHT_3,
                "Test ROMANTTF");
        /* 绘制二维码 */
        cxTspl.QRCode(300, 40 + 24 + 6 + 24 + 12, CXTspl.EEC.LEVEL_L, 8, CXTspl.ROTATION.ROTATION_0, " www.baidu.com");

        /* 绘制图片 */
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.cxprinter);
        cxTspl.Bitmap(100, 320, 150, 200, b, CXTspl.BITMAP_MODE.OVERWRITE.getValue());
        /* 清除打印缓冲区 */
//            cxTspl.Cls();
        /* 绘制一维条码 */
        cxTspl.Barcode(20, 250, CXTspl.BARCODETYPE.CODE128, 100, CXTspl.READABEL.EANBEL, CXTspl.ROTATION.ROTATION_0, "SMARNET");

        cxTspl.Circle(0, 0, 200, 2);
        /* 清除打印缓冲区 thickness以像素点为单位 */
        cxTspl.Box(0, 0, 576, 576, 1);
        cxTspl.Box(0, 576, 100, 576, 1);
        cxTspl.Line(430, 12, 648, 12, 43);
        /* 绘制直线 */
        cxTspl.Line(265, 25, 43, 453 - 265);
        cxTspl.Line(265, 25, 43, 178);


        cxTspl.Box(0, 0, 20, 20, 20);
        /* 打印标签 */
        cxTspl.Print(1, 1);
    }

    private void sendCpclData() {
        cxCpcl = CXCpcl.getInstance(cxcomm, 0);
        cxCpcl.PrintAreaSize(0, 200, 200, 576, 688, 1);
        cxCpcl.Box(0, 0, 576, 664, 2);
        cxCpcl.Line(0, 88, 576, 88, 1);
        cxCpcl.Line(0, 216, 576, 216, 1);
        cxCpcl.Line(0, 296, 576, 296, 1);
        cxCpcl.Line(0, 440, 528, 440, 1);
        cxCpcl.Line(0, 568, 528, 568, 1);
        cxCpcl.Line(0, 664, 528, 664, 1);
        cxCpcl.Line(528, 296, 528, 664, 1);
        cxCpcl.Line(48, 296, 48, 568, 1);
        cxCpcl.Align(CXCpcl.CENTER);
//            cxCpcl.Barcode(CXCpcl.BARCODE,CXCpcl.code128,"2","3","80","0","100",true,"8","0","5","363604310467");
        cxCpcl.Barcode(CXCpcl.BARCODE, CXCpcl.code128, "2", "3", "80", "0", "100", false, "0", "0", "0", "363604310467");
        cxCpcl.SetSp("12");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "0", "188", "363604310467");
        cxCpcl.SetSp("0");
        cxCpcl.SetMag("2", "2");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "0", "236", "上海 上海市 长宁区");
        cxCpcl.Align(CXCpcl.LEFT);
        cxCpcl.SetMag("1", "1");
        cxCpcl.SetBold("1");
        cxCpcl.Text(CXCpcl.TEXT, "4", "0", "64", "320", "申大通 13826514987");
        cxCpcl.Text(CXCpcl.TEXT, "4", "0", "64", "363", "上海市宝山区共和新路4719弄共");
        cxCpcl.Text(CXCpcl.TEXT, "4", "0", "64", "395", "和小区12号306室");
        cxCpcl.SetBold("0");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "13.6", "334.4", "收");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "13.6", "380.4", "件");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "13.6", "470.4", "发");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "13.6", "516.4", "件");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "64", "464", "快小宝 13826514987");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "64", "500.8", "上海市长宁区北曜路1178号（鑫达商务楼）");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "64", "528.8", "1号楼305室");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "541.6", "400", "派");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "541.6", "464", "件");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "541.6", "528", "联");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "16", "586.4", " 签收人/签收时间");
        cxCpcl.Text(CXCpcl.TEXT, "55", "0", "16", "615.2", " 你的签字代表您已验收此包裹，并已确认商品信息");
        cxCpcl.Text(CXCpcl.TEXT, "55", "0", "16", "639.2", " 无误,包装完好,没有划痕,破损等表面质量问题");
        cxCpcl.Text(CXCpcl.TEXT, "8", "0", "450", "629.2", " 月  日");
        /* 绘制图片 */
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.cxprinter);
        cxCpcl.Bitmap(10, 10, 60, 60, b, 0);
        cxCpcl.Form();
        cxCpcl.Print();

        cxCpcl.getDeviceInfo();
    }

    public void startScan() {
        CXBlueTooth.getInstance().scanDevices();
        Set<BluetoothDevice> paireDevices = CXBlueTooth.getInstance().getBondedDevices();
        Log.e(TAG, "paireDevices SIZE==" + paireDevices.size());
        if (paireDevices.size() > 0) {
            A:
            for (BluetoothDevice device : paireDevices) {
                for (DeviceScanBean list : lists) {
                    if (list.getBluetoothDevice().getAddress().equals(device.getAddress())) {
                        break A;
                    }
                }
                if (!TextUtils.isEmpty(device.getName())) {
                    lists.add(new DeviceScanBean(device, 0, new byte[0]));
                }
            }
        }
        if (lists.size() != 0) {
            mAdapter.setData(lists);
            mTv_none.setVisibility(View.GONE);
        }
        mImg_right.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.loading_animation));
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            mImg_right.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
        mHandler.sendEmptyMessageDelayed(MSG_STOP_SCAN, 5000);
    }


    private static final int REQUEST_ENABLE_BT = 1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUESTCODE_OPEN_BLE) {
            if (resultCode == Constants.RESULTCODE_OPEN_BLE) {
                if (!CXBlueTooth.getInstance().isBlueToothOpen()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                }
            } else if (resultCode == Constants.RESULTCODE_CLOSE_BLE) {
                finish();
            }
        } else if (requestCode == REQUEST_ENABLE_BT) {
            if (requestCode == REQUEST_ENABLE_BT) {
                if (resultCode == RESULT_OK) {
                    startScan();
                }
                if (resultCode == RESULT_CANCELED) {
                    finish();
                }
            } else {
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bind.unbind();
        mContext = null;
        mHandler.removeMessages(MSG_START_SCAN);
        mHandler.removeMessages(MSG_STOP_SCAN);
        CXBlueTooth.getInstance().stopScan();
        unregisterReceiver(receiver);
        if (mImg_right != null) {
            mImg_right.clearAnimation();
        }
    }


    public class ConnectDeviceRecyleViewAdapter extends RecyclerView.Adapter<ConnectDeviceRecyleViewAdapter.ViewHolder> {
        private Context mContext;

        private ArrayList<DeviceScanBean> lists = new ArrayList<DeviceScanBean>();

        public ConnectDeviceRecyleViewAdapter(Context context) {
            mContext = context;
        }


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            ViewHolder holder = new ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.connectdevice_recycleview_item, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder mHolder, final int position) {
            logShow("onBindViewHolder");
            mHolder.mTv_content.setText(lists.get(position).getDeviceName() + "\r\n" + lists.get(position).getMacAddress());
            if (position == lists.size()) {
                mHolder.view_short.setVisibility(View.GONE);
                mHolder.view_long.setVisibility(View.VISIBLE);
            } else {
                mHolder.view_short.setVisibility(View.VISIBLE);
                mHolder.view_long.setVisibility(View.GONE);
            }

            if (isConnect) {
                mHolder.mImg_loading.setVisibility(View.GONE);
                mHolder.mImg_loading.clearAnimation();
            } else {
                if (isConnecting && clickDeviceScanBean != null && clickDeviceScanBean.getMacAddress().equals(lists.get(position).getMacAddress())) {
                    mHolder.mImg_loading.setVisibility(View.VISIBLE);
                    mHolder.mImg_loading.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.loading_animation));
                    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                        mHolder.mImg_loading.setLayerType(View.LAYER_TYPE_HARDWARE, null);
                    }
                } else {
                    mHolder.mImg_loading.setVisibility(View.GONE);
                    mHolder.mImg_loading.clearAnimation();
                }
            }
            mHolder.mRl_recycleview_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isConnect) {
                        ToastUtil.showLong(getString(R.string.just_connect_onedevice));
                    } else {
                        if (isConnecting) {
                            ToastUtil.showLong(getString(R.string.just_connect_onedevice));
                        } else {
                            if (lists.size() != 0) {
                                deviceScanBean = lists.get(position);
                                if (deviceScanBean != null && deviceScanBean.getBluetoothDevice() != null) {
                                    CXBlueTooth.getInstance().stopScan();
                                    isConnecting = true;
                                    CXBlueTooth.getInstance().disconnect();
                                    CXBlueTooth.getInstance().conn(deviceScanBean.getBluetoothDevice());
                                    clickDeviceScanBean = deviceScanBean;
                                    mAdapter.notifyDataSetChanged();
                                }
                            }
                        }
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return lists.size();
        }

        public void setConnectList(DeviceScanBean deviceScanBean) {
            for (int i = 0; i < lists.size(); i++) {
                if (deviceScanBean != null && lists.get(i) != null) {
                    if (deviceScanBean.getMacAddress().equals(lists.get(i).getMacAddress())) {
                        lists.remove(i);
                    }
                }
            }
            this.notifyDataSetChanged();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.rl_recycleview_item)
            RelativeLayout mRl_recycleview_item;
            @BindView(R.id.tv_content)
            TextView mTv_content;
            @BindView(R.id.view_short)
            View view_short;
            @BindView(R.id.view_long)
            View view_long;
            @BindView(R.id.img_loading)
            ImageView mImg_loading;

            ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }
        }

        public void setData(ArrayList<DeviceScanBean> lists) {
            this.lists.clear();
            this.lists.addAll(lists);
            this.notifyDataSetChanged();
        }

        private void logShow(String str) {
            Log.e(TAG, str);
        }

    }

}